package com.young.filter;

import com.young.config.ProviderConfigProperty;
import com.young.service.ServiceAuthService;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.rpc.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Activate
@Component
public class TokenAuthFilter implements Filter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private ServiceAuthService serviceAuthService;

    private ProviderConfigProperty providerConfigProperty;

    public void setProviderConfigProperty(ProviderConfigProperty providerConfigProperty){
        this.providerConfigProperty=providerConfigProperty;
    }

    public void setServiceAuthService(ServiceAuthService serviceAuthService){
        this.serviceAuthService=serviceAuthService;
    }


    private static final String TOKEN_KEY="authorization";
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
//        String token = RpcContext.getServerAttachment().getAttachment(TOKEN_KEY);
//        String name = RpcContext.getServerAttachment().getAttachment("name");
//        System.out.println("token:"+token+",name:"+name);
//        if (token == null || !validateToken(token)) {
//            throw new RpcException("UnValid Token");
//        }
        String consumerName = RpcContext.getServerContext().getRemoteApplicationName();
        if (consumerName!=null){
            if (!serviceAuthService.canVisit(providerConfigProperty.getName(),consumerName)){
                throw new RpcException("UnValid Token");
            }
        }
        return invoker.invoke(invocation);
    }

    private boolean validateToken(String token) {
        String resToken = stringRedisTemplate.opsForValue().get(TOKEN_KEY);
        if (token.equals(resToken)) {
            return true;
        }
        return false;
    }
}
